import { NInput, NInputNumber } from 'naive-ui';
import type { PropType } from 'vue';

export enum ShowOrEditEnum {
	input,
	inputNumber,
}

const ShowOrEdit = defineComponent({
	props: {
		value: {
			type: [String, Number, Boolean] as PropType<string | number | boolean | null>,
			default: null,
		},
		onUpdateValue: {
			type: Function,
			default: () => {},
		},
		isEdit: {
			type: Boolean as PropType<boolean>,
			default: false,
		},
		type: {
			type: Number,
			default: ShowOrEditEnum.input,
		},
	},
	emits: ['update:value'],
	setup(props, { emit }) {
		const inputValue = ref(props.value);
		watch(
			() => props.value,
			(count, prevCount) => {
				inputValue.value = props.value;
			}
		);
		function handleChange() {
			emit('update:value', inputValue.value);
			props.onUpdateValue(unref(inputValue));
		}

		function getInputType() {
			if (props.type === ShowOrEditEnum.input) {
				return (
					<NInput
						value={inputValue.value as string}
						onUpdateValue={v => {
							inputValue.value = v;
						}}
						onChange={handleChange}
						onBlur={handleChange}
					/>
				);
			} else if (props.type === ShowOrEditEnum.inputNumber) {
				return (
					<NInputNumber
						value={inputValue.value as number}
						onUpdateValue={v => {
							inputValue.value = v;
							handleChange();
						}}
						onBlur={handleChange}
					/>
				);
			}
		}

		return () => (
			<div style={'min-height: 22px'}>{props.isEdit ? getInputType() : props.value}</div>
		);
	},
});

export default ShowOrEdit;
